/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.filters;

import com.huawei.housekeeper.constants.CommonConstants;
import com.huawei.housekeeper.utils.CommonUtil;
import com.huawei.housekeeper.utils.JwtTokenUtil;
import com.huawei.housekeeper.utils.LogAnonymizeUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 *
 * @author y00464350
 * @since 2022-02-23
 */
@Log4j2
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private LogAnonymizeUtil logAnonymizeUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        Thread currentThread = Thread.currentThread();
        currentThread.setName(request.getRequestURI() + ":" + CommonUtil.getUUID());
        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        String userId = null;
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());
            userId = jwtTokenUtil.getUserIdFromToken(authToken);
            String userName = jwtTokenUtil.getUserNameFromToken(authToken);

            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(userName);
                request.setAttribute(CommonConstants.User.USER_NAME, userName);
                if (!jwtTokenUtil.isTokenExpired(authToken)) {
                    UsernamePasswordAuthenticationToken authentication = new
                            UsernamePasswordAuthenticationToken(userDetails, null,
                            userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        String method = request.getMethod();
        log.info(logAnonymizeUtil.doAnonymize(
                request.getRequestURL() + ", userId: " + userId + ", method : " + method));
        chain.doFilter(request, response);
    }
}